package com.dinggao.crossgo.module.roadbook.activity;

import android.Manifest;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dinggao.crossgo.R;
import com.dinggao.crossgo.core.MainApplication;
import com.dinggao.crossgo.core.base.BaseActivity;
import com.dinggao.crossgo.core.constant.CommonConstant;
import com.dinggao.crossgo.core.dao.PathDao;
import com.dinggao.crossgo.core.dao.entity.Path;
import com.dinggao.crossgo.core.manage.ActivtyManager;
import com.dinggao.crossgo.core.manage.ApiManager;
import com.dinggao.crossgo.core.observer.EventIntet;
import com.dinggao.crossgo.core.observer.EventMsg;
import com.dinggao.crossgo.core.observer.PrivateObserver;
import com.dinggao.crossgo.core.paser.FastJsonUtils;
import com.dinggao.crossgo.core.util.LogUtils;
import com.dinggao.crossgo.core.util.ScreenUtil;
import com.dinggao.crossgo.core.util.SharedPreferencesUtil;
import com.dinggao.crossgo.core.util.ToastUtil;
import com.dinggao.crossgo.module.roadbook.adapter.RoadBookLeftAdapter;
import com.dinggao.crossgo.module.roadbook.adapter.RoadBookSubListAdapter;
import com.dinggao.crossgo.module.roadbook.data.RoadBookAddBean;
import com.dinggao.crossgo.module.roadbook.data.RoadBookLeftBean;
import com.dinggao.crossgo.module.roadbook.data.RoadBookNestTeamBean;
import com.dinggao.crossgo.module.roadbook.data.RoadBookSubListBean;
import com.dinggao.crossgo.module.roadbook.service.LocationService;
import com.dinggao.crossgo.module.user.login.LoginActivity;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wang.avi.AVLoadingIndicatorView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 发布路书页面
 * Created by Administrator on 2018/7/21.
 */

public class RoadBookPublishMainActivity extends BaseActivity implements PrivateObserver {

    @BindView(R.id.road_book_map)
    MapView roadBookMap;
    @BindView(R.id.road_book_control_bt)
    RelativeLayout roadBookControlBt;
    @BindView(R.id.road_book_child_list)
    RecyclerView roadBookChildList;
    @BindView(R.id.road_book_control_rt)
    LinearLayout roadBookControlRt;

    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.road_book_control_bt_icon)
    ImageView roadBookControlBtIcon;
    @BindView(R.id.road_book_control_bt_tv)
    TextView roadBookControlBtTv;
    @BindView(R.id.pbProgress)
    AVLoadingIndicatorView pbProgress;

    public static final String TAG = "MainActivity";
    @BindView(R.id.road_book_click_point)
    TextView roadBookClickPoint;
    @BindView(R.id.left_recyclerview)
    RecyclerView leftRecyclerview;
    @BindView(R.id.common_menu_publish_bt)
    TextView commonMenuPublishBt;
    //定义一个用于判断退出时的时间
    private long mExitTime;
    //定位返回纬度，经度
    private double currentLatitude, currentLongitude;
    private String currentLocation;

    //初始化地图控制器对象
    private AMap aMap;
    private AlarmManager am;
    private PendingIntent pendSender;
    private Polyline polyline;
    private Marker startMarker;
    private Marker currentMarker;
    private Marker positionMarker;
    //初始化策划lan
    private List<RoadBookLeftBean> leftBeanList = new ArrayList<>();
    private RoadBookLeftAdapter roadBookLeftAdapter;

    // 列表相关
    private List<RoadBookSubListBean.DataBean> roadBookSubListBeanList = new ArrayList<>();
    private RoadBookSubListAdapter roadBookSubListAdapter;
    private List<Marker> subListMarkList = new ArrayList<>();

    // 轨迹记录状态
    private static final String PATH_RECORDING = "recording";
    private static final String PATH_NO_START = "no_start";
    private static final String PATH_PAUSE = "pause";
    private String pathState = PATH_NO_START;
    private List<LatLng> pathList = new ArrayList<>();

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;

    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    // 加载状态Flag
    private boolean isFirstLoad = true;

    private String roadBookId = "";
    //发布是否公开网络参数
    private int status=1;

    /**
     * 声明广播接收器
     */
    private BroadcastReceiver locationReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                String longitude = intent.getStringExtra("longitude");
                String latitude = intent.getStringExtra("latitude");

                if (aMap != null) {
                    pathList.add(new LatLng(Double.valueOf(latitude), Double.valueOf(longitude)));
                    LogUtils.e("ceshi", "latitude" + Double.valueOf(latitude) + "longitude" + Double.valueOf(longitude));

                    updateMapPath();

                    if (PATH_RECORDING.equals(pathState)) {
                        aMap.animateCamera(CameraUpdateFactory
                                .newCameraPosition(new CameraPosition(new LatLng(Double.valueOf(latitude), Double.valueOf(longitude)), 18,
                                        0, 0)));
                    }
                }
            }
        }
    };


    @Override
    protected int getLayoutResource() {
        return R.layout.activity_road_book_publish_main;
    }

    @Override
    protected void onInitialization(Bundle bundle) {

        EventIntet.getDefault().register(this);
        /**初始化闹铃**/
        am = (AlarmManager)
                getSystemService(Context.ALARM_SERVICE);

        /**初始化UI**/
        // 子路书列表
        roadBookChildList.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, true));
        roadBookChildList.setNestedScrollingEnabled(false);
        roadBookSubListAdapter = new RoadBookSubListAdapter(roadBookSubListBeanList);
        roadBookChildList.setAdapter(roadBookSubListAdapter);
        new LinearSnapHelper().attachToRecyclerView(roadBookChildList);

        /**地图及定位相关初始化操作**/
        mLocationClient = new AMapLocationClient(this);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        // 高德地图: 此方法须覆写，虚拟机需要在很多情况下保存地图绘制的当前状态
        roadBookMap.onCreate(bundle);
        // 获取地图实例
        if (aMap == null) {
            aMap = roadBookMap.getMap();
        }
        // 初始化地图
        initMap();
        // 开启定位
        getLocation();
        // 注册定位广播
        IntentFilter readFilter = new IntentFilter(LocationService.ACTION_UPDATE_LOCATION);
        registerReceiver(locationReceiver, readFilter);


        //判断是否是第一次加载该界面
        boolean isFirist = SharedPreferencesUtil.getSharedPreferencesBoolean(RoadBookPublishMainActivity.this, CommonConstant.USERINFO_ISFIRST,
                CommonConstant.USERINFO_ISFIRST_VALUE);
        if (isFirist) {
            roadBookClickPoint.setVisibility(View.GONE);
        }
        /** 初始化侧边栏 **/
        initLeftView();

        /** 初始化路书数据 **/
        getCurrentRoadBook();

      //  LogUtils.e("dp","height:"+ScreenUtil.getScreenHeight(this)+"width:"+ScreenUtil.getScreenWidth(this));

    }

    /**
     * 侧滑栏设置
     */
    private void initLeftView() {

        View view = LayoutInflater.from(this).inflate(R.layout.layout_menu_header, null, false);
        TextView userNameText = ((TextView) view.findViewById(R.id.userNameText));
        ImageView headerImageView = (ImageView) view.findViewById(R.id.headerImageView);

        String headimage = SharedPreferencesUtil.getSharedPreferencesString(RoadBookPublishMainActivity.this,
                CommonConstant.USERINFO_SHREDPREFERENCE, CommonConstant.USERINFO_HEANDIMAGEURI);
        String phone = SharedPreferencesUtil.getSharedPreferencesString(RoadBookPublishMainActivity.this, CommonConstant.USERINFO_SHREDPREFERENCE,
                CommonConstant.USRERINFO_SHRAREDPREFERCE_PHONE_NUMBER);
        String nickName = SharedPreferencesUtil.getSharedPreferencesString(RoadBookPublishMainActivity.this, CommonConstant.USERINFO_SHREDPREFERENCE,
                CommonConstant.USERINFO_NICKNAME);
        boolean useWEIXIN = SharedPreferencesUtil.getSharedPreferencesBoolean(RoadBookPublishMainActivity.this,
                CommonConstant.USERINFO_SHREDPREFERENCE, CommonConstant.USERINFO_USEWEIXIN);


        leftBeanList.add(new RoadBookLeftBean(R.drawable.common_mine, "我的路书（2）", ""));

        //设置头像和昵称
        if (useWEIXIN) {
            userNameText.setText(nickName);
            leftBeanList.add(new RoadBookLeftBean(R.drawable.common_wx, "微信绑定", "已绑定"));
            Glide.with(this).load(headimage).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(headerImageView);
        } else {
            userNameText.setText(phone);
            leftBeanList.add(new RoadBookLeftBean(R.drawable.common_wx, "微信绑定", "未绑定"));
            Glide.with(this).load(getResources().getDrawable(R.mipmap.app_icon)).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(headerImageView);
        }

        leftBeanList.add(new RoadBookLeftBean(R.drawable.common_logout, "退出登录", ""));
        roadBookLeftAdapter = new RoadBookLeftAdapter(R.layout.item_main_rod_left, leftBeanList);
        leftRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        leftRecyclerview.setAdapter(roadBookLeftAdapter);
        roadBookLeftAdapter.setHeaderView(view);

        roadBookLeftAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                switch (position) {
                    case 0:
                        drawerLayout.closeDrawers();
                        startActivity(new Intent(RoadBookPublishMainActivity.this,RoadBookMineActivity.class));
                        break;
                    case 1:
                       // drawerLayout.closeDrawers();
                        TextView rightText = ((TextView) view.findViewById(R.id.text_right_left_item));
                        if (rightText.getText().toString().equals("未绑定")) {
                            String appId = CommonConstant.WECHAT_APPID; // 填应用AppId
                            IWXAPI api = WXAPIFactory.createWXAPI(RoadBookPublishMainActivity.this, appId);
                            if (api != null && api.isWXAppInstalled()) {
                                SendAuth.Req req = new SendAuth.Req();
                                req.scope = "snsapi_userinfo";
                                req.state = "wechat_sdk_demo_test";
                                api.sendReq(req);
                            } else {
                                Toast.makeText(RoadBookPublishMainActivity.this, "若想使用该功能，请您先安装微信", Toast.LENGTH_LONG).show();

                            }
                        } else {
                            Toast.makeText(RoadBookPublishMainActivity.this, "您已绑定微信", Toast.LENGTH_LONG).show();

                        }

                        break;
                    case 2:
                        drawerLayout.closeDrawers();
                        String userId = SharedPreferencesUtil.getSharedPreferencesString(RoadBookPublishMainActivity.this, CommonConstant.USERINFO_SHREDPREFERENCE,
                                CommonConstant.USERINFO_USERID);
                        OkGo.<String>post(ApiManager.AUTH_LOGOUT)
                                .headers("accessToken", SharedPreferencesUtil.getSharedPreferencesString(RoadBookPublishMainActivity.this, CommonConstant.USERINFO_SHREDPREFERENCE,
                                        CommonConstant.USRERINFO_SHRAREDPREFERCE_ACCESS_TOKEN))
                                .tag(this)
                                .params("userId", Integer.valueOf(userId))
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(Response<String> response) {

                                        LogUtils.e(TAG, response.body());
                                        SharedPreferencesUtil.clearPreferences(RoadBookPublishMainActivity.this, CommonConstant.USRERINFO_SHRAREDPREFERCE_ACCESS_TOKEN);
                                        startActivity(new Intent(RoadBookPublishMainActivity.this, LoginActivity.class));
                                        finish();
                                    }
                                });


                        break;

                }
            }
        });

    }

    /**
     * 初始化地图
     */
    private void initMap() {
        aMap.getUiSettings().setZoomControlsEnabled(false);
    //    aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 设置卫星地图模式，aMap是地图控制器对象。
        // 初始化轨迹
        PolylineOptions polylineOptions = new PolylineOptions();
        polylineOptions.width(16);
        polylineOptions.color(Color.parseColor("#ffd219"));
        polyline = aMap.addPolyline(polylineOptions);

        // 初始化轨迹开始marker与轨迹当前marker
        startMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.path_start_icon)));
        currentMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.path_position_icon)));
        positionMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 1f)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.common_current_position)));


    }

    /**
     * 启动定位
     */
    private void getLocation() {
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);

        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
        AMapLocationListener aMapLocationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        if (isFirstLoad) {
                            aMap.animateCamera(CameraUpdateFactory
                                    .newCameraPosition(new CameraPosition(new LatLng(aMapLocation.getLatitude(),
                                            aMapLocation.getLongitude()), 18,
                                            0, 0)));
                            isFirstLoad = false;
                        }

                        //可在其中解析amapLocation获取相应内容。
                        currentLatitude = aMapLocation.getLatitude();
                        currentLongitude = aMapLocation.getLongitude();
                        currentLocation = aMapLocation.getProvince() + aMapLocation.getCity() + aMapLocation.getDistrict() + aMapLocation.getStreet();

                        positionMarker.setPosition(new LatLng(aMapLocation.getLatitude(),
                                aMapLocation.getLongitude()));

//                        Log.e("瞬时定位", "瞬时定位"
//                                + currentLatitude + ","
//                                + currentLongitude + ","
//                                + currentLocation);
                    } else {
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        Log.e("AmapError", "location Error, ErrCode:"
                                + aMapLocation.getErrorCode() + ", errInfo:"
                                + aMapLocation.getErrorInfo());
                    }
                }
            }
        };

        mLocationClient.setLocationListener(aMapLocationListener);
    }

    /**
     * 获取当前路书
     * 路书的获取有两种情况（1.本地有未发布的路书 2.创建全新路书）
     */
    private void getCurrentRoadBook() {
        // 判断本地是否有未发布的路书
        String localRoadBookId = SharedPreferencesUtil.getSharedPreferencesString(RoadBookPublishMainActivity.this,
                CommonConstant.USERINFO_SHREDPREFERENCE,
                CommonConstant.USRERINFO_LOCAL_ROADBOOK_ID);

//        LogUtils.e(TAG, localRoadBookId);
        if (!TextUtils.isEmpty(localRoadBookId)) {
            // 1.本地有未发布的路书
            roadBookId = String.valueOf(localRoadBookId);
            initLocalRoadBook(roadBookId);
        } else {
            // 2.创建全新路书
            createRoadBook();
        }
    }

    /**
     * 创建新的路书
     */
    private void createRoadBook() {
        pbProgress.setVisibility(View.VISIBLE);
        pbProgress.show();
        OkGo.<String>post(ApiManager.ROADBOOK_ADD)
                .headers("accessToken", SharedPreferencesUtil.getSharedPreferencesString(RoadBookPublishMainActivity.this, CommonConstant.USERINFO_SHREDPREFERENCE,
                        CommonConstant.USRERINFO_SHRAREDPREFERCE_ACCESS_TOKEN))
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                       // LogUtils.e("tsg", result);
                        RoadBookAddBean roadBookAddBean = FastJsonUtils.getObject(result, RoadBookAddBean.class);

                        if (roadBookAddBean != null && roadBookAddBean.getData() != null && roadBookAddBean.getData().getStatus() == 0) {
                            // 记录路书未发布路书id到本地
                            SharedPreferencesUtil.setSharedPreferencesString(
                                    RoadBookPublishMainActivity.this,
                                    CommonConstant.USERINFO_SHREDPREFERENCE,
                                    CommonConstant.USRERINFO_LOCAL_ROADBOOK_ID,
                                    String.valueOf(roadBookAddBean.getData().getId()));

                            // 获取路书id
                            roadBookId = String.valueOf(roadBookAddBean.getData().getId());

                            initLocalRoadBook(roadBookId);
                            pbProgress.setVisibility(View.GONE);
                            pbProgress.hide();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        pbProgress.setVisibility(View.GONE);
                        pbProgress.hide();
                        ToastUtil.showLong(RoadBookPublishMainActivity.this, "创建路书失败");
                    }
                });
    }

    /**
     * 初始化本地路书
     */
    private void initLocalRoadBook(String roadBookId) {
        // 1. 初始化定位闹铃及定位服务
        Intent intent = new Intent(this, LocationService.class);
        pendSender = PendingIntent.getService(this, 0, intent, 0);
        stopService(intent);

        // 3. 初始化轨迹、轨迹Marker及轨迹按钮
        isFirstLoad = true;
        pathState = PATH_NO_START;
        startMarker.setVisible(false);
        currentMarker.setVisible(false);
        positionMarker.setVisible(true);
//        aMap.getUiSettings().setMyLocationButtonEnabled(true);
        pathList.clear();

        List<Path> paths =
                MainApplication.getDaoInstant().getPathDao().queryBuilder()
                        .where(PathDao.Properties.RoadBookId.eq(roadBookId)).list();

        if (paths != null && paths.size() != 0) {
            // 本地已记录过轨迹
            for (Path path : paths) {
                pathList.add(new LatLng(path.getLat(), path.getLng()));
            }
            // 展示已有的轨迹
            initMapMarkersForStartRecording();
//            aMap.getUiSettings().setMyLocationButtonEnabled(false);
            positionMarker.setVisible(false);
            updateMapPath();

            // 更新轨迹按钮
            pathState = PATH_PAUSE;
            updatePathButton();
        } else {
            startMarker.setVisible(false);
            currentMarker.setVisible(false);
//            aMap.getUiSettings().setMyLocationButtonEnabled(true);
            positionMarker.setVisible(true);
            updateMapPath();

            // 更新轨迹按钮
            pathState = PATH_NO_START;
            updatePathButton();
        }

        // 4. 初始化子路书列表及子路书Marker
        roadBookSubListBeanList.clear();
        roadBookSubListAdapter.notifyDataSetChanged();
        clearSubRoadBookMarker();

        // 获取子路书数据及Marker位置
        getListData();
        roadBookSubListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent detailIntent = new Intent(RoadBookPublishMainActivity.this, RoadBookPublishDetailsActivity.class);
                RoadBookSubListBean.DataBean dataBean = roadBookSubListBeanList.get(position);
                int journalId = dataBean.getId();
                detailIntent.putExtra("journalId", journalId + "");
                startActivity(detailIntent);
            }
        });
    }

    /**
     * 初始化列表数据
     */
    private void getListData() {
//        LogUtils.e("imagebean", roadBookId);
        OkGo.<String>get(ApiManager.ROADBOOKJOURNAL_LIST)
                .headers("accessToken", SharedPreferencesUtil.getSharedPreferencesString(RoadBookPublishMainActivity.this, CommonConstant.USERINFO_SHREDPREFERENCE,
                        CommonConstant.USRERINFO_SHRAREDPREFERCE_ACCESS_TOKEN))
                .params("roadBookId", roadBookId)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        //   LogUtils.e("imagebean", response.body());

                        RoadBookSubListBean listBean = FastJsonUtils.getObject(response.body(), RoadBookSubListBean.class);

                        if (listBean.getData() != null && listBean.getData().size() != 0) {
                            //  LogUtils.e("imagebean", response.body());
                            roadBookSubListBeanList.addAll(listBean.getData());
                            // roadBookSubListAdapter.notifyItemChanged(0);
                            roadBookSubListAdapter.notifyDataSetChanged();
                            roadBookChildList.setVisibility(View.VISIBLE);
                            roadBookChildList.scrollToPosition(0);
                            addSubRoadBookMarker(listBean);
                        } else {
                            roadBookChildList.setVisibility(View.GONE);
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LogUtils.e("TAG", response.getException().toString());
                    }
                });
    }

    /**
     * 添加子路书Marker
     */

    int journalId = 0;

    private void addSubRoadBookMarker(final RoadBookSubListBean listBean) {
        for (int i = 0; i < listBean.getData().size(); i++) {
            LatLng latLng = new LatLng(listBean.getData().get(i).getLatitude(), listBean.getData().get(i).getLongitude());
            journalId = listBean.getData().get(i).getId();
            MarkerOptions markerOption = new MarkerOptions();
            markerOption.position(latLng);
            markerOption.anchor(0.5f, 0.5f);
            markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                    .decodeResource(getResources(), R.drawable.path_point_icon)));
            Marker marker = aMap.addMarker(markerOption);
            subListMarkList.add(marker);

            //marker点击事件
            AMap.OnMarkerClickListener markerClickListener = new AMap.OnMarkerClickListener() {
                @Override
                public boolean onMarkerClick(Marker marker) {
                    Intent detailIntent = new Intent(RoadBookPublishMainActivity.this, RoadBookPublishDetailsActivity.class);
                    detailIntent.putExtra("journalId", journalId + "");
                    startActivity(detailIntent);
                    return false;
                }
            };

            aMap.setOnMarkerClickListener(markerClickListener);

        }
    }

    /**
     * 清除子路书Marker
     */
    private void clearSubRoadBookMarker() {
        for (int i = 0; i < subListMarkList.size(); i++) {
            subListMarkList.get(i).remove();
        }
        subListMarkList.clear();
    }

    /**
     * 开始记录轨迹
     */
    public void startPathRecord() {
        Intent intent = new Intent(this, LocationService.class);
        startService(intent);

        // 添加闹铃定时唤醒定位服务（周期为1分钟）
        am.cancel(pendSender);
        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 60 * 1000, pendSender);
    }

    /**
     * 停止记录轨迹
     */
    public void stopPathRecord() {
        am.cancel(pendSender);
        Intent intent = new Intent(this, LocationService.class);
        stopService(intent);
    }

    /**
     * 更新地图轨迹
     */
    private void updateMapPath() {
        polyline.setPoints(pathList);
        if (currentMarker != null) {
            for (int i = 0; i < pathList.size(); i++) {
                if (i == pathList.size() - 1) {
                    currentMarker.setPosition(pathList.get(i));
                }
            }
        }
    }

    /**
     * 添加轨迹地图Marker
     */
    private void initMapMarkersForStartRecording() {
        startMarker.setPosition(pathList.get(0));
        startMarker.setVisible(true);
        currentMarker.setPosition(pathList.get(pathList.size() - 1));
        currentMarker.setVisible(true);
    }

    /**
     * 根据当前记录轨迹状态更新按钮样式
     */
    private void updatePathButton() {
        switch (pathState) {
            case PATH_NO_START:
                roadBookControlBt.setBackgroundResource(R.drawable.path_record_black_bg);
                roadBookControlBtIcon.setVisibility(View.GONE);
                roadBookControlBtTv.setText("记录轨迹");
                roadBookControlBtTv.setTextColor(Color.parseColor("#ffffff"));
                break;
            case PATH_PAUSE:
                roadBookControlBt.setBackgroundResource(R.drawable.path_record_yellow_bg);
                roadBookControlBtIcon.setVisibility(View.VISIBLE);
                roadBookControlBtIcon.setImageResource(R.drawable.path_record_start);
                roadBookControlBtTv.setText("继续记录");
                roadBookControlBtTv.setTextColor(Color.parseColor("#141414"));
                break;
            case PATH_RECORDING:
                roadBookControlBt.setBackgroundResource(R.drawable.path_record_yellow_bg);
                roadBookControlBtIcon.setVisibility(View.VISIBLE);
                roadBookControlBtIcon.setImageResource(R.drawable.path_record_pause);
                roadBookControlBtTv.setText("记录中...");
                roadBookControlBtTv.setTextColor(Color.parseColor("#141414"));
                break;
            default:
                break;
        }
    }

    /**
     * 发布按钮弹窗
     *
     * @param teamName
     * @param teamId
     */
    private void showReleaseDialog(String teamName, final long teamId) {


        final Dialog dialog = new Dialog(this);//可以在style中设定dialog的样式
        dialog.setContentView(R.layout.dialog_release);
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.gravity = Gravity.CENTER;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        dialog.getWindow().setAttributes(lp);
        //设置该属性，dialog可以铺满屏幕
        dialog.getWindow().setBackgroundDrawable(null);
        final EditText editText = (EditText) dialog.findViewById(R.id.edit_dilog_release);
        if (teamName!=null){
            editText.setText(teamName);
            editText.setSelection(teamName.length());
        }


//        dialog.setOnShowListener(new DialogInterface.OnShowListener() {
//            @Override
//            public void onShow(DialogInterface dialog) {
//                editText.requestFocus();
//                InputMethodManager inputMethodManager =
//                        (InputMethodManager) RoadBookPublishMainActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
//                inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
//
//            }
//        });

        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                InputMethodManager inputMethodManager =
                        (InputMethodManager) RoadBookPublishMainActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(
                        RoadBookPublishMainActivity.this.getWindow().getDecorView().getWindowToken(), 0);
            }
        });

        dialog.show();
        CheckBox checkBox = (CheckBox) dialog.findViewById(R.id.checkbox_dialog_release);
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    status = 1;
                } else {
                    status = 2;
                }
            }
        });
        Button cancle = (Button) dialog.findViewById(R.id.dialog_release_cancel);
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                dialog.dismiss();
            }
        });
        Button sure = (Button) dialog.findViewById(R.id.dialog_release_sure);
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (editText.getText() != null && editText.getText().toString().length() > 0) {
                    submitRoadBook(teamId,editText.getText().toString() , status);
                    dialog.dismiss();
                } else {
                    ToastUtil.showLong(RoadBookPublishMainActivity.this, "请输入标题");
                }

            }
        });


    }

    /**
     * 重置按钮弹窗
     */
    private void showResetDialog() {
        final Dialog dialog = new Dialog(this);//可以在style中设定dialog的样式
        dialog.setContentView(R.layout.dialog_reset);
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.gravity = Gravity.CENTER;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        dialog.getWindow().setAttributes(lp);
        //设置该属性，dialog可以铺满屏幕
        dialog.getWindow().setBackgroundDrawable(null);


        dialog.show();
        Button cancle = (Button) dialog.findViewById(R.id.dialog_release_cancel);
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        Button sure = (Button) dialog.findViewById(R.id.dialog_release_sure);
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 创建新路书，并刷新页面
                createRoadBook();
                dialog.dismiss();
            }
        });
    }

    /**
     * 发布路书
     */
    private void submitRoadBook(long teamId, String title, int status) {
        // 获取路书轨迹
        String roadPaths = "";
        for (int i = 0; i < pathList.size(); i++) {
            roadPaths += pathList.get(i).longitude;
            roadPaths += " ";
            roadPaths += pathList.get(i).latitude;
            if (i != pathList.size() - 1) {
                roadPaths += ", ";
            }
        }

        LogUtils.e(TAG,status+"");
        OkGo.<String>post(ApiManager.ROADBOOK_UPDATE)
                .headers("accessToken", SharedPreferencesUtil.getSharedPreferencesString(RoadBookPublishMainActivity.this, CommonConstant.USERINFO_SHREDPREFERENCE,
                        CommonConstant.USRERINFO_SHRAREDPREFERCE_ACCESS_TOKEN))
              //  .headers("accessToken", "7cd23670-a003-42ea-9236-70a00332ea99")
                .params("roadId", roadBookId)
                .params("title", title)
                .params("teamId", teamId)
                .params("location", currentLocation)
                .params("status", status)//公开1，不公开2
                .params("roadPaths", roadPaths)
                .tag(this)

                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response != null) {
                            // 创建新路书，并刷新页面

                            createRoadBook();
                            Intent intent = new Intent(RoadBookPublishMainActivity.this, RoadBookPublishSuccessActivity.class);
                            startActivity(intent);

                        } else {
                            // 发布失败
                            Toast.makeText(RoadBookPublishMainActivity.this, "发布路书失败", Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Toast.makeText(RoadBookPublishMainActivity.this, "发布路书失败", Toast.LENGTH_LONG).show();
                    }
                });
    }

    @OnClick({
            R.id.road_book_click_point,
            R.id.road_book_control_bt,
            R.id.common_menu_bt,
            R.id.common_menu_publish_bt,
            R.id.road_book_bottom_text,
            R.id.road_book_bottom_photo,
            R.id.road_book_bottom_gallery,
            R.id.to_current_position_bt,
            R.id.common_menu_reset_bt})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.road_book_click_point:
                SharedPreferencesUtil.setSharedPreferencesBoolean(
                        RoadBookPublishMainActivity.this,
                        CommonConstant.USERINFO_ISFIRST,
                        CommonConstant.USERINFO_ISFIRST_VALUE, true);
                roadBookClickPoint.setVisibility(View.GONE);
                break;
            case R.id.to_current_position_bt:
                if (aMap != null) {
                    aMap.animateCamera(CameraUpdateFactory
                            .newCameraPosition(new CameraPosition(new LatLng(Double.valueOf(currentLatitude), Double.valueOf(currentLongitude)), 18,
                                    0, 0)));
                }
                break;
            case R.id.common_menu_bt:
                if (drawerLayout.isDrawerOpen(Gravity.LEFT)) {
                    // 关闭
                    drawerLayout.closeDrawer(Gravity.LEFT);
                } else {
                    // 打开
                    drawerLayout.openDrawer(Gravity.LEFT);
                }
                break;
            case R.id.common_menu_reset_bt:
                showResetDialog();
                break;
            case R.id.common_menu_publish_bt:
                // 发布路书

                if (PATH_RECORDING.equals(pathState)) {
                    Toast.makeText(RoadBookPublishMainActivity.this, "请先暂停记录轨迹", Toast.LENGTH_LONG).show();
                } else {
                    commonMenuPublishBt.setClickable(false);
                    OkGo.<String>get(ApiManager.ROADBOOK_GETNESTTEAM)
                            .headers("accessToken", SharedPreferencesUtil.getSharedPreferencesString(RoadBookPublishMainActivity.this, CommonConstant.USERINFO_SHREDPREFERENCE,
                                    CommonConstant.USRERINFO_SHRAREDPREFERCE_ACCESS_TOKEN))
                            .tag(this)
                            .execute(new StringCallback() {
                                @Override
                                public void onSuccess(Response<String> response) {
                                    LogUtils.e("response",response.body());
                                    RoadBookNestTeamBean roadBookNestTeamBean = FastJsonUtils.getObject(response.body(), RoadBookNestTeamBean.class);
                                    if (roadBookNestTeamBean != null && roadBookNestTeamBean.getCode() == 0) {

                                        long teamId = roadBookNestTeamBean.getData().getTeamId();
                                        String teamName = roadBookNestTeamBean.getData().getTeamName();
                                        showReleaseDialog(teamName,teamId);
                                        commonMenuPublishBt.setClickable(true);
                                    }


                                }

                                @Override
                                public void onError(Response<String> response) {
                                    super.onError(response);
                                    LogUtils.e("TAG", response.getException().toString());
                                    commonMenuPublishBt.setClickable(true);
                                }
                            });

                }


                break;
            case R.id.road_book_control_bt:
                switch (pathState) {
                    case PATH_NO_START: // 点击记录轨迹
                        // 获取到当前定位才可以进行轨迹记录
                        if (currentLatitude != 0.0d && currentLongitude != 0.0d) {
                            // 变更状态为记录中
                            pathState = PATH_RECORDING;
                            // 记录开始坐标
                            pathList.add(new LatLng(currentLatitude, currentLongitude));
                            Path path = new Path();
                            path.setRoadBookId(Long.valueOf(roadBookId));
                            path.setLat(currentLatitude);
                            path.setLng(currentLongitude);
                            MainApplication.getDaoInstant().getPathDao().insert(path);
                            // 更新地图元素
                            initMapMarkersForStartRecording();
//                            aMap.getUiSettings().setMyLocationButtonEnabled(false);
                            positionMarker.setVisible(false);
                            updateMapPath();
                            // 开启持续定位轨迹后台服务
                            startPathRecord();
                            // 更新轨道记录按钮
                            updatePathButton();
                        } else {
                            Toast.makeText(this, "未获取到当前定位,无法记录轨迹", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case PATH_RECORDING: // 点击记录中...

//                        if (aMap.getUiSettings().isMyLocationButtonEnabled()) {
//                            aMap.getUiSettings().setMyLocationButtonEnabled(false);
//                        }
                        positionMarker.setVisible(true);
                        // 变更状态为记录中
                        pathState = PATH_PAUSE;
                        // 关闭持续定位轨迹后台服务
                        stopPathRecord();
                        // 更新轨道记录按钮
                        updatePathButton();
                        break;
                    case PATH_PAUSE:  // 点击暂停记录
//                        if (!aMap.getUiSettings().isMyLocationButtonEnabled()) {
//                            aMap.getUiSettings().setMyLocationButtonEnabled(true);
//                        }
                        positionMarker.setVisible(false);
                        // 变更状态为记录中
                        pathState = PATH_RECORDING;
                        startPathRecord();
                        // 更新轨道记录按钮
                        updatePathButton();
                        break;
                    default:
                        break;
                }
                break;
            case R.id.road_book_bottom_text:
                // 点击文字发布
                LogUtils.e(TAG, "roadBookId:" + roadBookId + " Latitude:" + currentLatitude + "  Longitude:" + currentLongitude + "  location:" + currentLocation);
                getTakePhotoPermission(0);

                break;
            case R.id.road_book_bottom_photo:
                // 点击拍照发布
                getTakePhotoPermission(1);

                break;
            case R.id.road_book_bottom_gallery:
                // 点击选图片发布
                getTakePhotoPermission(2);

                break;
        }
    }


    /**
     * 对返回键进行监听
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {

                Toast.makeText(RoadBookPublishMainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                ActivtyManager.getAppManager().AppExit(this);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        EventIntet.getDefault().unregister(this);
        roadBookMap.onDestroy();
        unregisterReceiver(locationReceiver);
        mLocationClient.stopLocation();
        mLocationClient.onDestroy();
        mLocationOption = null;
        mLocationClient = null;

    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        roadBookMap.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        roadBookMap.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        roadBookMap.onSaveInstanceState(outState);
    }

    @Override
    public void update(Object obj) {
        if (!(obj instanceof EventMsg)) {
            return;
        }
        EventMsg eventMsg = (EventMsg) obj;
        //  LogUtils.e("TAG",eventMsg.getMsg()+"-_-"+eventMsg.getFrom()+"-_-"+eventMsg.getCode());
        if (eventMsg.getCode() == 9902) {
            roadBookSubListBeanList.clear();
            getListData();
            LogUtils.e("imagebean", "!!!!!" + "!!!!");
        }

        if (eventMsg.getCode() == 9999) {
            leftBeanList.clear();
            initLeftView();
        }

    }


    private void getTakePhotoPermission(final int position) {
        RxPermissions rxPermissions = new RxPermissions(RoadBookPublishMainActivity.this);
        rxPermissions.request(Manifest.permission.CAMERA)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean aBoolean) {

                        if (aBoolean) {
                            switch (position) {
                                case 0:
                                    if (currentLatitude != 0 && currentLongitude != 0 && currentLocation != null) {
                                        Intent intentText = new Intent(RoadBookPublishMainActivity.this, RoadBookPublishReleaseActivity.class);
                                        intentText.putExtra("number", String.valueOf(0));

                                        intentText.putExtra("roadBookId", Integer.valueOf(roadBookId));
                                        intentText.putExtra("Latitude", currentLatitude);
                                        intentText.putExtra("Longitude", currentLongitude);
                                        intentText.putExtra("location", currentLocation);
                                        startActivity(intentText);

                                    } else {
                                        Toast.makeText(RoadBookPublishMainActivity.this, "未获取到当前定位,无法打点", Toast.LENGTH_SHORT).show();
                                    }
                                    break;
                                case 1:
                                    if (currentLatitude != 0 && currentLongitude != 0 && currentLocation != null) {
                                        Intent intentPhoto = new Intent(RoadBookPublishMainActivity.this, RoadBookPublishReleaseActivity.class);
                                        intentPhoto.putExtra("number", String.valueOf(1));
                                        intentPhoto.putExtra("roadBookId", Integer.valueOf(roadBookId));
                                        intentPhoto.putExtra("Latitude", currentLatitude);
                                        intentPhoto.putExtra("Longitude", currentLongitude);
                                        intentPhoto.putExtra("location", currentLocation);
                                        startActivity(intentPhoto);
                                    } else {
                                        Toast.makeText(RoadBookPublishMainActivity.this, "未获取到当前定位,无法打点", Toast.LENGTH_SHORT).show();
                                    }
                                    break;
                                case 2:
                                    if (currentLatitude != 0 && currentLongitude != 0 && currentLocation != null) {
                                        Intent intentGallery = new Intent(RoadBookPublishMainActivity.this, RoadBookPublishReleaseActivity.class);
                                        intentGallery.putExtra("number", String.valueOf(2));
                                        intentGallery.putExtra("roadBookId", Integer.valueOf(roadBookId));
                                        intentGallery.putExtra("Latitude", currentLatitude);
                                        intentGallery.putExtra("Longitude", currentLongitude);
                                        intentGallery.putExtra("location", currentLocation);
                                        startActivity(intentGallery);
                                    } else {
                                        Toast.makeText(RoadBookPublishMainActivity.this, "未获取到当前定位,无法打点", Toast.LENGTH_SHORT).show();
                                    }
                                    break;
                            }

                        } else {

                            AlertDialog mPermissionDialog = new AlertDialog.Builder(RoadBookPublishMainActivity.this)
                                    .setMessage("已禁用权限，请手动授予")
                                    .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Uri packageURI = Uri.parse("package:" + RoadBookPublishMainActivity.this.getPackageName());
                                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                                            startActivity(intent);
                                        }
                                    })
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                            ToastUtil.showLong(RoadBookPublishMainActivity.this, "请赋予相机权限");

                                        }
                                    })
                                    .create();
                            mPermissionDialog.show();

                        }


                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
